package com.ruoyi.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.dto.RoleDTO;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.oa.service.IOaHumanClockService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.oa.domain.bo.OaHumanReplaceBo;
import com.ruoyi.oa.domain.vo.OaHumanReplaceVo;
import com.ruoyi.oa.domain.OaHumanReplace;
import com.ruoyi.oa.mapper.OaHumanReplaceMapper;
import com.ruoyi.oa.service.IOaHumanReplaceService;
import com.ruoyi.workflow.service.IProcessInstanceService;
import com.ruoyi.workflow.service.IUserService;
import com.ruoyi.workflow.utils.WorkFlowUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.stream.Collectors;
import java.util.*;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.oa.domain.vo.OaProjectVo;

/**
 * 补卡申请Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-07
 */
@RequiredArgsConstructor
@Service
public class OaHumanReplaceServiceImpl implements IOaHumanReplaceService {

    private final OaHumanReplaceMapper baseMapper;

    private final IProcessInstanceService iProcessInstanceService;

    private final IUserService iUserService;

    private final IOaHumanClockService iOaHumanClockService;
    /**
     * 查询补卡申请
     */
    @Override
    public OaHumanReplaceVo queryById(String id){
        OaHumanReplaceVo vo= baseMapper.selectVoById(id);
        WorkFlowUtils.setStatusFileValue(vo,vo.getId());
        return vo;
    }


    /**
     * 补卡申请领导们都同意了，然后修改考勤记录
     * @param id
     * @throws ParseException
     */
    @Override
    public void replaceInfo(String id) throws ParseException {
        OaHumanReplaceVo vo= baseMapper.selectVoById(id);
        iOaHumanClockService.adjustApply(vo);
    }

    /**
     * 查询补卡申请列表
     */
    @Override
    public TableDataInfo<OaHumanReplaceVo> queryPageList(OaHumanReplaceBo bo, PageQuery pageQuery) {
        LoginUser currentUser = LoginHelper.getLoginUser();
        List<RoleDTO> roles = currentUser.getRoles();
        if (CollectionUtil.isNotEmpty(roles)){
            List<RoleDTO> roleDTOS = roles.stream().filter(d -> d.getRoleId()==(116)||d.getRoleId()==(1)).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(roleDTOS)){
                bo.setCreateUser(currentUser.getUsername());
            }
        }
        if (StringUtils.isNotBlank(bo.getCreateBy())) {
            String userName = iUserService.getUserNameByNickName(bo.getCreateBy());
            if (StringUtils.isNotBlank(userName)) {
                bo.setCreateBy(userName);
            }
        }
        if (CollectionUtil.isNotEmpty(bo.getSubmitTimeList())){
            bo.setSubmitStartDate(bo.getSubmitTimeList().get(0));
            bo.setSubmitEndDate(bo.getSubmitTimeList().get(1));
        }
        List<OaHumanReplaceVo> voList = baseMapper.queryByCondition(bo);
        // 添加流程信息
        if (CollectionUtil.isNotEmpty(voList)) {
            List<String> list = voList.stream().map(OaHumanReplaceVo::getId).collect(Collectors.toList());
            WorkFlowUtils.setStatusListFileValue(voList, list, "id");
        }
        // 筛选状态
        if (StringUtils.isNotBlank(bo.getStatus())) {
            List<OaHumanReplaceVo> temp = new ArrayList<>();
            for (OaHumanReplaceVo vo : voList) {
                if (vo.getActBusinessStatus().getStatus().equals(bo.getStatus())) {
                    temp.add(vo);
                }
            }
            voList = temp;
        }
        // 筛选提交时间
        if (CollectionUtil.isNotEmpty(bo.getSubmitTimeList())) {
            List<OaHumanReplaceVo> temp = new ArrayList<>();
            Date submitStartDate = bo.getSubmitStartDate();
            Date submitEndDate = bo.getSubmitEndDate();
            for (OaHumanReplaceVo vo : voList) {
                Date createTime = vo.getActBusinessStatus().getCreateTime();
                if (ObjectUtil.isNotEmpty(createTime) && createTime.after(submitStartDate) && createTime.before(submitEndDate)) {
                    temp.add(vo);
                }
            }
            voList = temp;
        }

        // 筛选提交人
        if (StringUtils.isNotEmpty(bo.getCreateBy())) {
            List<OaHumanReplaceVo> temp = new ArrayList<>();
            for (OaHumanReplaceVo vo : voList) {
                if (ObjectUtil.isNotEmpty(vo.getActBusinessStatus().getCreateTime()) && vo.getActBusinessStatus().getCreateBy().equals(bo.getCreateBy())) {
                    temp.add(vo);
                }
            }
            voList = temp;
        }
        Page<OaHumanReplaceVo> result = new Page<>();
        result.setTotal(voList.size());

        int start = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        int end = Math.min(pageQuery.getPageNum() * pageQuery.getPageSize(), voList.size());
        voList = voList.subList(start, end);

        result.setRecords(voList);
        result.setCurrent(pageQuery.getPageNum());
        result.setSize(pageQuery.getPageSize());

        return TableDataInfo.build(result);
    }

    /**
     * 查询补卡申请列表
     */
    @Override
    public List<OaHumanReplaceVo> queryList(OaHumanReplaceBo bo) {
        LambdaQueryWrapper<OaHumanReplace> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OaHumanReplace> buildQueryWrapper(OaHumanReplaceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OaHumanReplace> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getReplaceReason()), OaHumanReplace::getReplaceReason, bo.getReplaceReason());
        lqw.eq(bo.getReplaceTime() != null, OaHumanReplace::getReplaceTime, bo.getReplaceTime());
        lqw.eq(StringUtils.isNotBlank(bo.getReplaceMatter()), OaHumanReplace::getReplaceMatter, bo.getReplaceMatter());
        return lqw;
    }

    /**
     * 新增补卡申请
     */
    @Override
    public OaHumanReplaceBo insertByBo(OaHumanReplaceBo bo) {
        LoginUser currentUser = LoginHelper.getLoginUser();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String month = sdf.format(bo.getReplaceTime());
        JSONObject replaceInfo = iOaHumanClockService.getUserReplaceInfo(currentUser.getUserId().toString(), month);
        if (replaceInfo.getBoolean("hasData")){
            if (replaceInfo.getInteger("remainTotal")>0){
                Boolean chance = iOaHumanClockService.checkDateHasChance(currentUser.getUserId().toString(), bo.getReplaceTime());
                if (chance){
                    bo.setDeptId(currentUser.getDeptId());
                    bo.setUserId(currentUser.getUserId());
                    OaHumanReplace add = BeanUtil.toBean(bo, OaHumanReplace.class);
                    validEntityBeforeSave(add);
                    boolean flag = baseMapper.insert(add) > 0;
                    if (flag) {
                        bo.setId(add.getId());
                    }
                    return bo;
                }else {
                    return null;
                }
            }else {
                return null;
            }
        }else {
            return null;
        }
    }




    /**
     * 修改补卡申请
     */
    @Override
    public OaHumanReplace updateByBo(OaHumanReplaceBo bo) {
        LoginUser currentUser = LoginHelper.getLoginUser();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String month = sdf.format(bo.getReplaceTime());
        JSONObject replaceInfo = iOaHumanClockService.getUserReplaceInfo(currentUser.getUserId().toString(), month);
        if (replaceInfo.getBoolean("hasData")) {
            if (replaceInfo.getInteger("remainTotal") > 0) {
                Boolean chance = iOaHumanClockService.checkDateHasChance(currentUser.getUserId().toString(), bo.getReplaceTime());
                if (chance) {
                    OaHumanReplace update = BeanUtil.toBean(bo, OaHumanReplace.class);
                    validEntityBeforeSave(update);
                    int i = baseMapper.updateById(update);
                    return update;
                }else {
                    return null;
                }
            } else {
                return null;
            }
        }else {
            return null;
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OaHumanReplace entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除补卡申请
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        for (String id : ids) {
            String processInstanceId = iProcessInstanceService.getProcessInstanceId(id);
            if (StringUtils.isNotBlank(processInstanceId)) {
                iProcessInstanceService.deleteRuntimeProcessAndHisInst(processInstanceId);
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 通过月份和id获取本月补卡次数
     * @param month
     * @param userId
     * @return
     */
    @Override
    public Integer getUserReplaceByMonth(String month, String userId) {
        List<OaHumanReplaceVo> list = baseMapper.getUserReplaceByMonth(month, userId);
        if (CollectionUtil.isNotEmpty(list)) {
            List<String> Idlist = list.stream().map(OaHumanReplaceVo::getId).collect(Collectors.toList());
            WorkFlowUtils.setStatusListFileValue(list, Idlist, "id");
        }

        if (CollectionUtil.isNotEmpty(list)) {
            list = list.stream().filter(d -> d.getActBusinessStatus().getStatus().equals("finish")).collect(Collectors.toList());
        }

        return list.size();
    }
}
